﻿-module (acrs).
-include("mk.hrl").
-compile (export_all).

reload_data() -> 
  begin
	merle:connect("localhost", 11211),
	io:format("Done 00 ~p~n" ,[erlang:localtime()]),
	gen_subs(lists:seq(1,1000)),
	io:format("Done 00 ~p~n" ,[erlang:localtime()]),
	%%spawn(gen_subs_range(1,25000)),
	%%spawn(gen_subs_range(25001,50000)),
	%%spawn(gen_subs_range(50001,75000)),
	%%spawn(gen_subs_range(75001,100000)),
	%%run_rng(lists:seq(1,1000)),
	io:format("Done ~p~n" ,[erlang:localtime()]),
	
	merle:set(cmp,acrs_test_data:test_get_cmp_list())	
  end.
  
  
run_rng([H|T]) ->
  spawn(gen_subs_range(H*100,H*100+100)),
  run_rng(T);
run_rng([]) -> io:format("Done ~p~n" ,[erlang:localtime()]).


gen_subs_range(FromId, ToId) -> 
  (fun() -> 
    %%FromId+ToId
	gen_subs(lists:seq(FromId,ToId))
	%%io:format("Done ~p~n" ,[erlang:localtime()])
  end).
  
  
gen_subs([H|T]) ->
  merle:set(integer_to_list(H),acrs_test_data:test_get_subs_profile()),
  gen_subs(T);
gen_subs([]) -> [].


dt1_gr_dt2(D1,D2) ->
  calendar:datetime_to_gregorian_seconds(D1) > calendar:datetime_to_gregorian_seconds(D2).
  
datetime_is_future(D) ->
  dt1_gr_dt2(D,erlang:localtime()).
  
  
get_subs_profile(_SubsId) -> 
  acrs_test_data:test_get_subs_profile().
  

%% 1 
%% отбирам только те кампании у которых есть указанный в запросе канал
%% возвращаем [{канал, кампания},...]
fa (CmpList, ChannelName) -> [ 
{lists:keyfind(ChannelName,3,C#campaign.chennels),C} ||
  C <- CmpList,
  lists:keyfind(ChannelName,3,C#campaign.chennels) /= false
].

%% 2
%% отбираем те кампании у которых есть предложение для уазанного в запросе канала
%% возвращаем [{оффер, кампания},...]
fb (Cmp_fa) -> [ 
{lists:keyfind(ChId,3,C#campaign.offers),C} ||
  {{_,ChId,_},C} <- Cmp_fa,
  lists:keyfind(ChId,3,C#campaign.offers) /= false
].

%% 3
%% отбираем только те кампании для которых есть предложения в профиле
fc (Cmp_fb,Prf) -> [
  {COffer, C} ||
  {COffer,C} <- Cmp_fb,
  {PCmp,POfferId,PWave} <- Prf,
  C#campaign.id =:= PCmp,
  COffer#offer.id =:= POfferId
].

%% 4
%% отбираем только те кампании которые действуют по политике показа
fd (Cmp_fc) -> [
   C || {_,C} <- Cmp_fc
].


cmp_is_active() -> 
 (fun(Cmp) -> 
        (not datetime_is_future(Cmp#campaign.start_date)) 
    and (    datetime_is_future(Cmp#campaign.end_date))
  end).
  
	
cmp_less() -> 
  (fun(L,R) ->
    if ( (L#campaign.priority /= R#campaign.priority)) ->
		 (L#campaign.priority =< R#campaign.priority);
		true -> false
	end
  end).

acrs_query_subs_campaign(SubsID, ChennelName) -> 
	merle:connect("localhost", 11211),
    Pr =  merle:getkey(SubsID),
    lists:sort(cmp_less(),
		fd(
			fc(
				fb(
					fa(
						lists:filter(cmp_is_active(), merle:getkey(cmp)),
						ChennelName
					)
				),
				Pr
			)
		)
	).
	
	
%%unicode:characters_to_binary()	
cmpList2xml([H|T]) ->
	cmp2xml(H) ++ cmpList2xml(T);
cmpList2xml([]) -> "".
	
	

acrs_register_response(_SubsId, _CmpId, _OfferId) -> 
	merle:set(33,1001).
	
	
cmp2xml(Cmp) -> 
	"<MARKETING_OFFER>"++
	"<CAMPAIGN_URI>urn:billing.ru:gup:acrs-market-campaign:"++io_lib:format("~p",[Cmp#campaign.id])++"</CAMPAIGN_URI>"++
    "<CAMPAIGN_METADATA>" ++
	"<CAMPAIGNID>" ++ io_lib:format("~p",[Cmp#campaign.id])++ "</CAMPAIGNID>" ++
	"<NAME>" ++ io_lib:format("~p",[Cmp#campaign.name]) ++ "</NAME>"++
	%%chennels2xml(Cmp#campaign.chennels) ++
	"<START_DATE>" ++ io_lib:format("~p",[Cmp#campaign.start_date]) ++ "</START_DATE>" ++
	"<END_DATE>" ++ io_lib:format("~p",[Cmp#campaign.end_date]) ++ "</END_DATE>" ++
    "</CAMPAIGN_METADATA>" ++	
	
	"</MARKETING_OFFER>".
	
chennels2xml(Chennels) ->	
"<CHANNELS><CHANNEL ID=/"1/"><TYPE><![CDATA[SCC_BANNERS]]></TYPE></CHANNEL><CHANNEL ID=/"2/"><TYPE><![CDATA[SCC_CMPLIST]]></TYPE></CHANNEL><CHANNEL ID=3><TYPE><![CDATA[SCC_USSD]]></TYPE></CHANNEL><CHANNEL ID=4><TYPE><![CDATA[CIS_MEC]]></TYPE></CHANNEL></CHANNELS>"
.	
